<template>
  <div class="Device-container">
    <v-skeleton-loader
      v-if="loading"
      height="100%"
      type="list-item@20"
    ></v-skeleton-loader>
    <Table
      v-else
      :headers="headers"
      :items="items"
      :showHeaderAction="false"
      disable-sort
      hide-default-footer
      @edit="openEditDevice"
      @delete="openDeleteDevice"
    >
    </Table>
    <Dialog
      width="480"
      @submit="saveDevice"
      :show-save="step !== 3"
      :title="dialogTitle"
      v-model="showDialog"
    >
      <template>
        <AddEditDevice
          v-if="step === 1 || step === 2"
          :type="step === 1 ? 'add' : 'edit'"
          ref="addEditDevice"
        ></AddEditDevice>
        <DeleteDevice
          v-else-if="step === 3 && selectedItem"
          :item="selectedItem"
          @delete="deleteDevice"
        ></DeleteDevice>
      </template>
    </Dialog>
  </div>
</template>

<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import Table from "@/components/Maintenance/Table/Table.vue";
import Dialog from "@/components/Maintenance/Dialog/Dialog.vue";
import AddEditDevice from "@/components/Maintenance/Admin/Device/AddEditDevice.vue";
import DeleteDevice from "@/components/Maintenance/Admin/Device/DeleteDevice.vue";
import { Omit, Pick } from "@/common/constants/Utils";
interface IDeviceItem {
  id: string;
  userId: string;
  userName: string;
  deviceId: string;
  status: string;
}
@Component({
  components: {
    Table,
    Dialog,
    AddEditDevice,
    DeleteDevice,
  },
})
export default class Device extends Vue {
  loading = false;
  // 1.AddDevice 2.EditDevice 2.DeleteDevice
  step = -1;
  // dialog
  showDialog = false;
  dialogTitle = "";
  openDialog() {
    this.showDialog = true;
  }
  closeDialog() {
    this.showDialog = false;
  }
  // Table
  selectedItem: IDeviceItem | null = null;
  items: IDeviceItem[] = [];
  headers = [
    {
      text: "User ID",
      value: "userId",
    },
    {
      text: "User Name",
      value: "userName",
    },
    {
      text: "Device ID",
      value: "deviceId",
    },
    {
      text: "Status",
      value: "status",
    },
    {
      value: "action",
    },
  ];
  getItems() {
    this.loading = true;
    setTimeout(() => {
      this.items = [
        {
          id: "1",
          userId: "AC",
          userName: "Amy Chan",
          deviceId: "4E91EA61A913745E",
          status: "Approved",
        },
        {
          id: "2",
          userId: "MK",
          userName: "Mark Wong",
          deviceId: "2704DD2E-3E47-4CEF-BC9C-592EA6A76584",
          status: "Approved",
        },
        {
          id: "3",
          userId: "NC",
          userName: "Nicole Chan",
          deviceId: "CBAB4274-0D45-4F25-A4BE-DF809A1A3ECF",
          status: "Approved",
        },
      ];
      this.loading = false;
    }, 1500);
  }

  // action
  openAddDevice() {
    this.step = 1;
    this.dialogTitle = "Add Device";
    this.$nextTick(() => {
      (this.$refs.addEditDevice as AddEditDevice).resetForm();
    });
    this.openDialog();
  }
  openEditDevice(item: IDeviceItem) {
    this.step = 2;
    this.dialogTitle = "Edit Device";
    this.$nextTick(() => {
      const addEditDeviceRef = this.$refs.addEditDevice as AddEditDevice;
      addEditDeviceRef.resetForm();
      setTimeout(() => {
        const backfillData = Object.assign(Omit(item, ["userName"]), {
          userId: `${item.userId}- ${item.userName}`,
        });
        console.log(backfillData);
        addEditDeviceRef.setFormData(backfillData);
      });
    });
    this.openDialog();
  }
  openDeleteDevice(item: IDeviceItem) {
    this.step = 3;
    this.dialogTitle = "Delete Device";
    this.selectedItem = item;
    this.openDialog();
  }

  addDevice(
    result: Pick<AddEditDevice, "userId" | "deviceId" | "status" | "id">
  ) {
    const [userId, userName] = result.userId!.split("- ");
    // add
    const device = {
      id: `${new Date().getTime()}`,
      userId,
      userName,
      status: "Not approved",
      deviceId: result.deviceId!,
    };
    this.items.push(device);
  }

  editDevice(
    result: Pick<AddEditDevice, "userId" | "deviceId" | "status" | "id">
  ) {
    const [userId, userName] = result.userId!.split("- ");
    const index = this.items.findIndex((item) => item.id === result.id);
    if (index !== -1) {
      Object.assign(
        this.items[index],
        { ...result },
        {
          userId,
          userName,
        }
      );
    }
  }

  deleteDevice() {
    const deviceItemId = (this.selectedItem as IDeviceItem).id;
    const index = this.items.findIndex((item) => item.id === deviceItemId);
    this.items.splice(index, 1);
    this.selectedItem = null;
    this.closeDialog();
  }

  saveDevice() {
    const addEditDeviceRef = this.$refs.addEditDevice as AddEditDevice;
    addEditDeviceRef.validateFormData().then((result) => {
      if (result) {
        if (result.id) {
          // edit
          this.editDevice(result);
        } else {
          this.addDevice(result);
        }
        this.closeDialog();
      }
    });
  }

  created() {
    this.getItems();
  }

  mounted() {
    this.$bus.$on("clickAction", this.openAddDevice);
    this.$store.commit("MaintenanceStore/switchActionIcon", "mdi-plus-thick");
  }

  destroyed() {
    console.log("destroyedDevice");
    this.$bus.$off("clickAction");
  }
}
</script>

<style lang="scss" scoped>
@import "./Device.scss";
</style>
